<?php
declare (strict_types = 1);

namespace App\Models;

/**
 * 用户账单表
 */
class UserBillModel extends BaseModel
{
    const UPDATED_AT = null;
    protected $table = 'user_bill';

    protected static $billType = [
        'system_add' => '系统增加',
        'system_sub' => '系统扣除',
    ];
    public static function getBillType($type)
    {
        return self::$billType[$type];
    }

    /**
     * 根据用户uid/关联id，获取对应数据
     * @param  [type] $user_id  用户id
     * @param  [type] $link_id  关联id
     * @param  [type] $type     类型：参考初始billType定义变量
     * @param  [type] $pm     1获得， 0支出
     * @param  string $category 种类：balance、integral
     * @return [type]           [description]
     */
    public static function getUserBill($user_id, $link_id, $type, $pm = 1, $category = 'balance', $is_show = 0)
    {
        $res = self::where([
            'uid' => $user_id,
            'link_id' => $link_id,
            'type' => $type,
            'pm' => $pm,
            'category' => $category,
        ])->first();
        return $is_show == 0 ? sprintf("%.2f",$res['number']) : $res;
    }

	/**
	 * 账单处理_后台增加余额、积分
	 * @param  array  $data 二维数组
	 * @return [type]       [description]
	 */
    public static function operateBill($data = [])
    {
    	try {
    		if(!$data || !is_array($data)) return self::result("", 500, "系统繁忙，请重试");
    		self::startTrans();
    		$list = self::insert($data);
    		if($list){
    			foreach ($data as $k => $v) {
    				$user = UserModel::find($v['uid']);
    				if(!$user) continue;
    				if($v['category'] == 'balance' && $v['number']){
    					$map["user_balance"] = $v['pm'] == 1 ? ($user['user_balance'] * 1 + $v['number']) : ($user['user_balance'] * 1 - $v['number']);
    				}
    				if($v['category'] == 'integral' && $v['number']){
    					$map["integral"] = $v['pm'] == 1 ? ($user['integral'] * 1 + $v['number']) : ($user['integral'] * 1 - $v['number']);
    				}
    				if(!$map) continue;
    				UserModel::where("uid",$user['uid'])->update($map);
    			}
    		}
            if(!$list){
                self::rollback();
                return self::result('', 500, "操作失败");
            }
            self::commit();
            return self::result('', 200, "操作成功");
    	} catch (\Exception $e) {
            self::rollback();
            return self::result("", 500, $e->getMessage());
    	}
    }

    /**
    * 生成对应账单
    * @param  array  $param [description]
    * @return [type]        [description]
    */
    public static function billCreate($param = [])
    {
        try {
            $res = self::create($param);
            return $res ? true : false;
        } catch (\Exception $e) {
            return false;
        }
    }

    /**
     * 余额、积分明细
     */
    public static function getBalanceList($pageSize, $page, $map)
    {
        $field = ['id', 'number', 'balance', 'mark', 'title', 'create_time', 'status'];

        $list = self::select($field)->where($map)
            ->orderBy('create_time','desc')
            ->paginate($pageSize,[],'page', $page)->toArray();

        if($list['data']){
            foreach ($list['data'] as $k => &$v) {
                $v['status'] = $v['status'] == 1 ? "有效" : ($v['status'] == 0 ? "待确认" : "无效");
                $v['create_time'] = $v['create_time'] ? date('Y-m-d H:i:s',$v['create_time']) : '';
            }
        }
        return $list;
    }
}
